// 定义生成账单的函数，接收两个参数：
// invoice：包含客户信息和演出列表的账单对象
// plays：包含所有演出信息的对象（以playID为键）
function statement (invoice, plays) {
    let totalAmount = 0;
    let volumeCredits = 0;
    let result = `Statement for ${invoice.customer}\n`;
    const format = new Intl.NumberFormat("en-US",
        { style: "currency", currency: "USD",
            minimumFractionDigits: 2 }).format;
    for (let perf of invoice.performances) {
        const play = playFor(perf);
        let thisAmount = amountFor(perf, playFor(perf));
// add volume credits
        volumeCredits += Math.max(perf.audience - 30, 0);
// add extra credit for every ten comedy attendees
        if ("comedy" === play.type) volumeCredits += Math.floor(perf.audience / 5);
// print line for this order
        result += ` ${play.name}: ${format(thisAmount/100)} (${perf.audience} seats)\n`;
        totalAmount += thisAmount;
    }
    result += `Amount owed is ${format(totalAmount/100)}\n`;
    result += `You earned ${volumeCredits} credits\n`;
    return result;

}

function playFor(aPerformance) {
    return plays[aPerformance.playID];
}


function amountFor(perf, play) {
    let thisAmount = 0;
    switch (play.type) {
        case "tragedy":
            thisAmount = 40000;
            if (perf.audience > 30) {
                thisAmount += 1000 * (perf.audience - 30);
            }
            break;
        case "comedy":
            thisAmount = 30000;
            if (perf.audience > 20) {
                thisAmount += 10000 + 500 * (perf.audience - 20);
            }
            thisAmount += 300 * perf.audience;
            break;
        default:
            throw new Error(`unknown type: ${play.type}`);
    }
    return thisAmount;
}

// 定义演出数据的JSON字符串（包含各演出的名称和类型）
const playsStr = `{
  "hamlet": {"name": "Hamlet", "type": "tragedy"},
  "as-like": {"name": "As You Like It", "type": "comedy"},
  "othello": {"name": "Othello", "type": "tragedy"}
}`;
// 将JSON字符串解析为JavaScript对象，便于访问演出信息
const plays = JSON.parse(playsStr);

// 定义账单数据的JSON字符串（包含客户信息和各演出的观看人数）
const invoicesStr = `[
  {
    "customer": "BigCo",
    "performances": [
      {
        "playID": "hamlet",
        "audience": 55
      },
      {
        "playID": "as-like",
        "audience": 35
      },
      {
        "playID": "othello",
        "audience": 40
      }
    ]
  }
]`;
// 将JSON字符串解析为JavaScript数组，便于访问账单信息
const invoices = JSON.parse(invoicesStr);

// 调用statement函数生成账单（传入数组中的第一个账单对象和演出信息）
const result = statement(invoices[0], plays);
// 在控制台打印生成的账单
console.log(result);